import { login, logout, getInfo } from "@/api/user";
import host from "@/utils/host";
import { getToken, setToken, removeToken } from "@/utils/auth";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",
    introduction: "",
    roles: [],
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { account, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ account: account.trim(), password: password })
        .then((response) => {
          const { data } = response;
          commit("SET_TOKEN", data);
          setToken(data);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          const { data } = response;
          if (!data) {
            return reject("验证失败！请重新登录");
          }

          const { license, name, avatar, introduction } = data;
          let roles = [];
          if (data.status == 2) {
            if (license) {
              roles = [license];
            } else {
              //默认是PA
              roles = ["PA"];
            }
          } else {
            roles = ["admin"];
          }

          // roles must be a non-empty array
          // 如果roles为空，则表明无法访问
          if (!roles || roles.length <= 0) {
            reject("角色信息必须是一个非空数组！");
          }

          commit("SET_ROLES", roles);
          commit("SET_NAME", name);
          if (!avatar) {
            const defaultAvatar = new URL(
              "@/assets/avatar.png",
              import.meta.url
            ).href;
            commit("SET_AVATAR", defaultAvatar);
          } else {
            commit("SET_AVATAR", avatar);
          }

          commit("SET_INTRODUCTION", introduction);
          data.roles = roles;
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    if (!state.token || state.token == undefined) {
      return;
    }
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken(); // must remove  token  first
          commit("RESET_STATE");
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
